package com.mbyte.easy.sign.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mbyte.easy.email.MailService;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.sign.entity.Sign;
import com.mbyte.easy.sign.service.ISignService;
import com.mbyte.easy.student.entity.Student;
import com.mbyte.easy.student.service.IStudentService;
import com.mbyte.easy.studentInfo.entity.TStudent;
import com.mbyte.easy.studentInfo.mapper.TStudentMapper;
import com.mbyte.easy.studentInfo.service.ITStudentService;
import com.mbyte.easy.vacation.entity.Vacation;
import com.mbyte.easy.vacation.service.IVacationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.chrono.ChronoLocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时任务类(wq2020.6.17)
 */
@Async
@Component
public class ScheduledService {

    @Autowired
    private IStudentService studentService;
    @Autowired
    private ITStudentService itStudentService;
    @Autowired
    private ISignService signService;
    @Autowired
    private MailService mailService;
    @Resource
    private TemplateEngine templateEngine;
    @Autowired
    private IVacationService vacationService;
    @Autowired
    private TStudentMapper studentMapper;
    @Autowired
    private IUserService userService;
    
    //每隔一个小时发送检查一次请假的表
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void vacation(){
        System.err.println("验证一次");
        List<Vacation> list = vacationService.list();
        for (int i = 0; i < list.size(); i++) {
            Vacation vacation = list.get(i);
            if(vacation.getVerifyStatus() == 0){
                continue;
            }
            LocalDateTime startTime = vacation.getStartTime();
            LocalDateTime endTime = vacation.getEndTime();
            TStudent tStudent = studentMapper.selectByUserId(vacation.getUserId());
            if(startTime.isBefore(LocalDateTime.now()) && endTime.isAfter(LocalDateTime.now())){
                vacation.setVacationStatus(1);
                vacationService.updateById(vacation);
                tStudent.setSex(5);
                itStudentService.updateById(tStudent);
            }else if (endTime.isBefore(LocalDateTime.now())){
                vacation.setVacationStatus(2);
                vacationService.updateById(vacation);
                tStudent.setSex(vacation.getMyStatus());
                itStudentService.updateById(tStudent);
            }
        }
    }
    //每天9 14 1  9点发送打卡任务
    @Scheduled(cron = "0 0 9,14,19 * * ?")
    public void scheduled(){
        //筛选非找工作阶段，非请假阶段的学生
        List<Student> stus = studentService.list(new LambdaQueryWrapper<Student>().in(Student::getSex,1,2,3));
        ArrayList<Sign> signs = new ArrayList<Sign>(stus.size());
        for (int i = 0 ;i < stus.size();i++){
            Sign sign = new Sign();
            sign.setUserId(stus.get(i).getUserId());
            sign.setClassId(stus.get(i).getClassId());
            sign.setSignStatus(0);
            sign.setDeleteStatus(0);
            signs.add(sign);
        }
        //将所有符合的学生批量插入数据库
        boolean b = signService.saveBatch(signs);
        System.out.println("插入打卡任务："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+b);
    }
    //定时邮件提醒任务，每晚9.30清算三天打卡次数(wq2020.6.18)
    @Scheduled(cron = "0 30 21 ? * *")
    public void scheduled1() throws MessagingException {
        //筛选非找工作阶段，非请假阶段的学生
        List<Student> alls = studentService.list(new LambdaQueryWrapper<Student>().in(Student::getSex,1,2,3));
        for (Student all : alls) {
            String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
            Calendar calendar = Calendar.getInstance();//获取对日期操作的类对象
            //在当前时间的基础上获取前两天的日期
            calendar.add(Calendar.DATE, -2);
            String two_days_ago = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            //筛选某人三天未打卡记录
            List<Sign> list = signService.list(new LambdaQueryWrapper<Sign>().eq(Sign::getUserId, all.getUserId()).between(Sign::getCreateTime, two_days_ago + Sign.ALLDAYSTARTTIME, now + Sign.ALLDAYOVERTIME).eq(Sign::getSignStatus,0).eq(Sign::getDeleteStatus,0));
            //查过三天9次卡没打，自动发送提醒打卡邮件
            if (list.size()>=9){
                Context context = new Context();
                String emailContent = templateEngine.process("email/signEmail", context);
                if (all.getEmail() == null)return;
                mailService.sendHtmlMail(all.getEmail(),"青城博雅打卡邮件",emailContent);
                System.out.println("邮件发送成功");
            }
        }


    }
//    @Scheduled(fixedRate = 5000)
//    public void scheduled1() {
//        System.out.println("=====>>>>>使用fixedRate{}"+System.currentTimeMillis());
//    }
//    @Scheduled(fixedDelay = 5000)
//    public void scheduled2() {
//        System.out.println("=====>>>>>fixedDelay{}"+System.currentTimeMillis());
//    }
}
